import axios from "axios";
import {stringify} from 'qs';
import {KEY} from './../store'
export const API_URL = "http://localhost:8090"
// 全局的请求路径
axios.defaults.baseURL = API_URL
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    config.headers['token'] = localStorage.getItem(KEY.token);
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

function processApiRequest(promise) {
    return new Promise(((resolve, reject) => {
        promise.then(ret => {
            if (ret.data && ret.data.code == 0) {
                resolve(ret.data.data);
            } else if (ret.data) {
                reject(new Error(ret.data.message))
            } else {
                reject(new Error('服务器响应的数据不正确'))
            }
        }).catch(err => {
            reject(new Error(err.message || err))
        })
    }))
}

/**
 * 接口操作
 * @param api
 * @param params
 * @returns {Promise<any>}
 */
export function get(api, params = {}) {
    return processApiRequest(axios.get(api + '?' + stringify(params)))
}

export function post(api, params = {}, dataType = 'json') {
    if (dataType == 'json') {
        return processApiRequest(axios.post(api, params));
    } else {
        return processApiRequest(axios.post(api, stringify(params), {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        }))
    }
}

export const request = axios.request

export default {
    get,
    post,
    request,
    API_URL
}
